<?php
namespace App\Repositories;

use App\Model\PaperQuestion;
use App\Traits\SingletonTrait;
use Hyperf\DbConnection\Db;

class PaperQuestionRepository extends AbstractRepository
{
    use SingletonTrait;

    public function model()
    {
        return 'App\\Model\\PaperQuestion';
    }

    public function store($data)
    {
        $model = isset($data['id'])&&$data['id']?$this->getById($data['id']):new $this->model();
        $model->fill($data);
        $answers = isset($data['answers'])?$data['answers']:[];
        $answer_text ='';
        $right_result = '';
        if($data['type']==PaperQuestion::TYPE_INPUT){
            $answers=[];
        }else{
            if(!empty($answers)){
                foreach ($answers as $key=>&$item){
                    $item['id'] = $key+1;
                    $item['char_num']=chr($key+65);
                    $answer_text.=$item['value'].',';
                    if($item['is_right']=='true'){
                        $right_result.=$item['char_num'];
                    }
                }
            }
        }
        $model->answers = json_encode($answers);
        $model->right_result = $right_result;
        //$model->search_txt=$data['title'].'|'.rtrim($answer_text,',');
        if(!$model->save()){
            return $this->error('保存失败');
        }
        return $this->success($model);
    }
}